#include "win32.h"
#include <iostream>
#include "win32socket.h"
#include "socket.h"
#include "taskmanager.h"
#include "xmpplogintask.h"
#include "xmpppresencetask.h"
#include "xmpprostertask.h"
#include "XmlParser.h"
#include "constants.h"
#include <process.h>

using namespace tinkle;

typedef struct _LoginData {
    std::string user;
    std::string pwd;
} LoginData;

unsigned __stdcall LoginThread(void *pArguments);

Win32Socket sock;
XmppLoginTask *task;
XmppPresenceTask *pTask;
XmppRosterTask *rTask;
StanzaManager *sMgr;
TaskManager *mgr;

int main() {
    //std::cout << stanza->Dump() << std::endl;
    //input user name and password
    /*LoginData data;
    std::cout << "User name: ";
    std::cin >> data.user;
    std::cout << "Password: ";
    std::cin >> data.pwd;

    unsigned threadId;
    HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, &LoginThread, &data,
        0, &threadId);

    std::string buf = "";
    while (buf != "quit") {
        std::cin >> buf;
    }*/
    sock.Connect("talk.google.com", "5222");
    unsigned threadId;
    HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, &LoginThread, NULL,
        0, &threadId);
    XmlParser parser;
    sMgr = new StanzaManager(sock, parser);
    mgr = new TaskManager(sMgr);
    task = new XmppLoginTask("testtinkle", "forourtest", mgr);
    pTask = new XmppPresenceTask(mgr);
    rTask = new XmppRosterTask(mgr);
    //task->Start();
    
    //Sleep(3000);
    //sock.Write(START_STREAM.c_str(), START_STREAM.length());
    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return 0;
}

unsigned __stdcall LoginThread(void *pArguments) {
    printf ("Connecting...\n");
    Sleep(1000);
    //sMgr->Write(START_STREAM);
    //Sleep(1000);
    //XmlNode *newStanza = new XmlNode("starttls");
    //(*newStanza)()->DeclNameSpace(NS_TLS, "");
    //printf ("%s\n", newStanza->Dump().c_str());
    //sMgr->Write(newStanza);
    task->Start();
    
 
    pTask->Start();
    
    Sleep(7000);
    rTask->GetRoster();
    //pTask->SetState(XmppPresenceTask::ONLINE);
    //Sleep(1000);
    //std::string str = "<stream:stream to=\"gmail.com\" version=\"1.0\" xmlns:stream=\"http://etherx.jabber.org/streams\" xmlns=\"jabber:client\">";
    //std::string str = "<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\"/>";
    //printf ("%s\n", str.c_str());
    //std::string str = START_STREAM->Dump();
    //printf ("%s\n", str.c_str());
    return 0;
}